import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import { Message } from "element-ui";
// 创建axios实例
const Http = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间,
})

// request拦截器
Http.interceptors.request.use(
  config => {
    // Do something before request is sent

    store.commit('SET_LINEARPROGRESS', true)
    if (store.state.login.token) {
      config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

Http.interceptors.response.use(
  function(response) {
    store.commit('SET_LINEARPROGRESS', false)

    // 对响应数据做点什么
    if (!response.data.success) {
      store.dispatch('openPopup', {
        message: response.data.message,
        type: 'error'
      })
      return false
    }
    return response
  },
  function(error) {
    // 对响应错误做点什么
    store.commit('SET_LINEARPROGRESS', false)

    store.dispatch('openPopup', {
      message: error.response.data.message,
      type: 'error'
    })

    return Promise.reject(error)
  }
)

export default Http
